import os
import re

class PathManager:
    def __init__(self, config_file="paths.txt"):
        self.config_file = config_file
        self.wechat_paths = []
        self.load_paths()
    
    def load_paths(self):
        """从配置文件加载路径"""
        try:
            if not os.path.exists(self.config_file):
                print(f"配置文件 {self.config_file} 不存在，使用默认路径")
                self.wechat_paths = [
                    "D:\\WXWork\\WXWork.exe",
                    "C:\\Program Files\\WXWork\\WXWork.exe",
                    "C:\\Program Files (x86)\\WXWork\\WXWork.exe"
                ]
                return

            with open(self.config_file, 'r', encoding='utf-8') as f:
                content = f.read()

            # 解析主要路径
            main_path_match = re.search(r'WECHAT_PATH=(.+)', content)
            if main_path_match:
                main_path = main_path_match.group(1).strip()
                # 验证路径格式和存在性
                if main_path:
                    if not main_path.lower().endswith('wxwork.exe'):
                        print(f"警告：主要路径可能不正确（应以WXWork.exe结尾）: {main_path}")
                    if os.path.exists(main_path):
                        self.wechat_paths.append(main_path)
                        print(f"已加载主要路径: {main_path}")
                    else:
                        print(f"警告：主要路径不存在: {main_path}")
                else:
                    print("警告：主要路径为空")

            # 解析备用路径
            backup_section = re.search(r'BACKUP_PATHS=\[(.*?)\]', content, re.DOTALL)
            if backup_section:
                backup_paths = backup_section.group(1).strip().split('\n')
                valid_backup_paths = 0
                for path in backup_paths:
                    path = path.strip()
                    if path:  # 只处理非空路径
                        if not path.lower().endswith('wxwork.exe'):
                            print(f"警告：备用路径可能不正确（应以WXWork.exe结尾）: {path}")
                            continue
                        if os.path.exists(path):
                            if path not in self.wechat_paths:
                                self.wechat_paths.append(path)
                                print(f"已加载备用路径: {path}")
                                valid_backup_paths += 1
                        else:
                            print(f"警告：备用路径不存在: {path}")
                    else:
                        print("跳过空备用路径")

                if valid_backup_paths == 0 and backup_paths:
                    print("警告：所有备用路径都无效")
            else:
                print("未找到备用路径配置段")

            # 如果没有找到任何有效路径，使用默认路径
            if not self.wechat_paths:
                print("配置文件中未找到有效路径，使用默认路径")
                self.wechat_paths = [
                    "D:\\WXWork\\WXWork.exe",
                    "C:\\Program Files\\WXWork\\WXWork.exe",
                    "C:\\Program Files (x86)\\WXWork\\WXWork.exe"
                ]
            else:
                print(f"成功加载 {len(self.wechat_paths)} 个有效路径")

        except UnicodeDecodeError as e:
            print(f"配置文件编码错误，请确保文件使用UTF-8编码: {e}")
            self.wechat_paths = [
                "D:\\WXWork\\WXWork.exe",
                "C:\\Program Files\\WXWork\\WXWork.exe",
                "C:\\Program Files (x86)\\WXWork\\WXWork.exe"
            ]
        except Exception as e:
            print(f"加载路径配置时出错: {e}")
            # 使用默认路径
            self.wechat_paths = [
                "D:\\WXWork\\WXWork.exe",
                "C:\\Program Files\\WXWork\\WXWork.exe",
                "C:\\Program Files (x86)\\WXWork\\WXWork.exe"
            ]
    
    def get_wechat_path(self):
        """获取企业微信可执行文件路径"""
        for path in self.wechat_paths:
            if os.path.exists(path):
                print(f"找到企业微信路径: {path}")
                return path
        
        print("未找到企业微信可执行文件，请检查配置文件中的路径设置")
        return None
    
    def add_path(self, path):
        """添加新的路径到配置"""
        if path not in self.wechat_paths:
            self.wechat_paths.append(path)
            print(f"已添加新路径: {path}")
    
    def save_config(self):
        """保存配置到文件"""
        try:
            with open(self.config_file, 'w', encoding='utf-8') as f:
                f.write("# 企业微信路径配置文件\n")
                f.write("# 请根据你的企业微信安装位置修改下面的路径\n")
                f.write("# 支持多个路径，程序会自动尝试找到正确的路径\n\n")
                
                if self.wechat_paths:
                    f.write(f"# 主要路径（推荐修改这里）\n")
                    f.write(f"WECHAT_PATH={self.wechat_paths[0]}\n\n")
                    
                    if len(self.wechat_paths) > 1:
                        f.write("# 备用路径（如果主要路径不存在，程序会尝试这些路径）\n")
                        f.write("BACKUP_PATHS=[\n")
                        for path in self.wechat_paths[1:]:
                            f.write(f"{path}\n")
                        f.write("]\n\n")
                
                f.write("# 说明：\n")
                f.write("# 1. 请将 WECHAT_PATH 修改为你的企业微信实际安装路径\n")
                f.write("# 2. 路径中使用双反斜杠 \\\\ 或正斜杠 /\n")
                f.write("# 3. 如果主要路径不存在，程序会自动尝试备用路径\n")
                f.write("# 4. 修改后保存文件，重启程序即可生效\n")
            
            print(f"配置已保存到 {self.config_file}")
            
        except Exception as e:
            print(f"保存配置时出错: {e}")

# 创建全局路径管理器实例
path_manager = PathManager()
